package com.community.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.communit.dto.CollectionDto;
import com.community.entity.Article;
import com.community.entity.ArticleCollection;
import com.community.service.IArticleCollectionService;
import com.community.service.IArticleService;

@Controller
@RequestMapping("/collection")
public class CollectionController {
	@Autowired
	private IArticleCollectionService iArticleCollectionService;
	@Autowired
	private IArticleService iArticleService;
	
	@RequestMapping()
	public String collection(HttpSession session,ModelMap modelMap){
		if(session.getAttribute("userid") == null){
			return "/user/login";
		}else{
			Long id = Long.valueOf(session.getAttribute("userid").toString());
			List<ArticleCollection> CollectionList = iArticleCollectionService.getArticleCollectionListByUserid(id);
			List<CollectionDto> CollectionDtoList = new ArrayList<>();
			CollectionDto collectionDto;
			for (ArticleCollection articleCollection : CollectionList) {
				collectionDto = new CollectionDto();
				Article a = iArticleService.getArticleById(articleCollection.getArticleid());
				BeanUtils.copyProperties(a, collectionDto);
				collectionDto.setCollectionId(articleCollection.getId());
				CollectionDtoList.add(collectionDto);
			}
			modelMap.addAttribute("CollectionDtoList", CollectionDtoList);
			return "/collection/collection";
		}
		
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public int addCollection(Long articleid,HttpSession session){
		if(session.getAttribute("userid") == null){
			return 0;
		}else{
			Long id = Long.valueOf(session.getAttribute("userid").toString());
			ArticleCollection ac = iArticleCollectionService.getArticleCollectionByUseridAndArticleid(id, articleid);
			if(ac == null){
				ArticleCollection a = new ArticleCollection();
				a.setArticleid(articleid);
				a.setUserid(id);
				iArticleCollectionService.addArticleCollection(a);
				return 1;
			}else{
				return 2;
			}
		}
	}
	
	@RequestMapping("/cancle")
	@ResponseBody
	public int cancleCollection(Long collectionid){
		ArticleCollection a = iArticleCollectionService.getArticleCollectionById(collectionid);
		iArticleCollectionService.deleteCollection(a);
		return 0;
	}

}
